import { Notification } from 'element-ui'

/**
 * @param {File} file
 * @param {Array} fileTypes ['image/png', 'image/jpeg']
 * @param {String} maxSize     500K, 1M
 */
export function isLegalFile(file, fileTypes, maxSize) {
  const isLegalFileType = (fileTypes.indexOf(file.type) >= 0)
  if (!isLegalFileType) {
    let suffixes = []
    fileTypes.forEach(type => {
      suffixes.push(type.substring(type.indexOf('/') + 1))
    })
    Notification.error({
      title: '图片格式不符要求',
      message: '允许的图片格式: ' + suffixes.join(', '),
      offset: 100,
      duration: 2000
    })
    return false
  }

  let units = ['k', 'K', 'M']
  let unit = maxSize.substring(maxSize.length - 1)
  let max = maxSize.substring(0, maxSize.length - 1)
  const isLegalFileSize = file.size / Math.pow(1024, units.indexOf(unit)) <= max
  if (!isLegalFileSize) {
    Notification.error({
      title: '图片太大',
      message: '图片大小不能超过' + maxSize,
      offset: 100,
      duration: 2000
    })
    return false
  }

  return true
}
